<!--
 * @Author: alenjzhang
 * @Date: 2024-03-20 20:56:30
 * @Description: 头像上传
-->
<script setup lang="ts">
import { DeleteOutlined, EyeOutlined } from '@ant-design/icons-vue'
import { type Ref, ref, watchEffect } from 'vue'
import { deleteCos, uploadCos } from '@/api'
import { useCustomForm } from '@/hooks'
// import { useBase64 } from '@vueuse/core';

// import { Empty } from 'ant-design-vue';

// const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;

const props = defineProps<{
  value?: string
  readonly?: boolean
  add?: boolean
}>()
const emits = defineEmits(['update:value'])
const field = useCustomForm()
const avatar = ref() as Ref<File>
// const { base64 } = useBase64(avatar);

const cosUrl = ref('')

function beforeUpload(file: File) {
  avatar.value = file
  handleChange(file)
  return false
}

watchEffect(() => {
  emits('update:value', cosUrl.value)
  field.onFieldChange()
})

watchEffect(() => {
  if (props.value)
    cosUrl.value = props.value
})

async function handleChange(file: File) {
  const res = await uploadCos(file)
  cosUrl.value = res.Data?.Url || ''
}

function remove(e: Event, url: string) {
  deleteCos([url]).send()
  e.preventDefault()
  cosUrl.value = ''
}
</script>

<template>
  <div v-if="!props.value && props.readonly" class="p10 pt20 pb20 text-center bd-#999 opacity-50">
    暂无头像
  </div>
  <a-image v-else-if="props.value" placeholder :width="props.add ? 200 : '100%'" :src="cosUrl">
    <template #previewMask>
      <div class="flex gap-10">
        <EyeOutlined />
        <div v-if="!props.readonly" @click="(e) => remove(e, cosUrl)">
          <DeleteOutlined />
        </div>
      </div>
    </template>
  </a-image>
  <div v-else class="w-100">
    <a-upload
      v-model="avatar" :max-count="1" :show-upload-list="false"
      name="avatar" list-type="picture-card" :before-upload="beforeUpload"
    >
      上传
    </a-upload>
  </div>
</template>
